package com.jinunn.system.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jinunn.system.common.result.Result;
import com.jinunn.system.model.params.RoleMenusParam;
import com.jinunn.system.model.params.RoleParam;
import com.jinunn.system.model.query.RolePageQuery;
import com.jinunn.system.model.vo.role.RolePageVO;
import com.jinunn.system.service.RoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author Jindun
 * @version RoleController.java, v0.1 2024年 07⽉ 12⽇  下午5:07 Jindun Exp $
 */
@Tag(name = "角色管理")
@RestController
@RequestMapping("/api/v1/role")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class RoleController {

    private final RoleService roleService;

    @Operation(summary = "角色分页列表")
    @PostMapping("/page")
    public Result<Page<RolePageVO>> getRolePage(@RequestBody RolePageQuery queryParams) {
        Page<RolePageVO> result = roleService.getPage(queryParams);
        return Result.success(result);
    }

    @Operation(summary = "新增角色")
    @PostMapping("/add")
    @PreAuthorize("@ss.hasPerm('sys:role:add')")
    public Result<Boolean> addRole(@Valid @RequestBody RoleParam roleForm) {
        boolean result = roleService.saveRole(roleForm);
        return Result.judge(result);
    }

    @Operation(summary = "修改角色")
    @PutMapping(value = "/edit")
    @PreAuthorize("@ss.hasPerm('sys:role:edit')")
    public Result<Boolean> updateRole(@Valid @RequestBody RoleParam roleForm) {
        boolean result = roleService.editRole(roleForm);
        return Result.judge(result);
    }

    @Operation(summary = "删除角色")
    @DeleteMapping("/{id}")
    @PreAuthorize("@ss.hasPerm('sys:role:delete')")
    public Result<Boolean> deleteRole(@Parameter(description = "删除角色") @PathVariable Long id) {
        boolean result = roleService.deleteRole(id);
        return Result.judge(result);
    }

    @Operation(summary = "分配菜单(包括按钮权限)给角色")
    @PostMapping("/menus")
    public Result<Boolean> assignMenusToRole(@RequestBody @Validated RoleMenusParam param) {
        boolean result = roleService.assignMenusToRole(param);
        return Result.judge(result);
    }
}
